<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessageBox, ElMessage, ElNotification } from 'element-plus'
import { getProductList, addProduct, deleteProduct, updateProduct, initSocket, onUserStatusChanged, offUserStatusChanged, onNewAnnouncement, offNewAnnouncement } from '../api/auth'
import request from '../api/auth'


interface Product {
  _id: string
  name: string
  description: string
  price: number
  image: string
  images: string[]
  stock: number
  sales: number
  isUp: boolean
  Tabs: string[]
  topCategoryInfo?: {
    _id: string
    name: string
  }
  subCategoryInfo?: {
    _id: string
    name: string
  }
  userId?: string
  createdAt?: string
  updatedAt?: string
}

const categories = ref<any[]>([])
const statusOptions = ['上架', '下架']

const searchForm = ref({
  id: '',
  name: '',
  category: '',
  status: ''
})

// 添加商品对话框相关数据
const addDialogVisible = ref(false)
const addForm = ref({
  name: '',
  description: '',
  price: 0,
  image: '',
  images: [],
  stock: 100,
  topCategory: '',
  subCategory: '',
  isUp: false,
  Tabs: []
})

const addFormRules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  image: [{ required: true, message: '请输入商品图片', trigger: 'blur' }],
  topCategory: [{ required: true, message: '请选择大分类', trigger: 'change' }],
  subCategory: [{ required: true, message: '请选择小分类', trigger: 'change' }]
}

const subCategories = ref<any[]>([])

// 编辑商品对话框相关数据
const editDialogVisible = ref(false)
const editForm = ref({
  _id: '',
  name: '',
  description: '',
  price: 0,
  image: '',
  images: [] as string[],
  stock: 100,
  topCategory: '',
  subCategory: '',
  isUp: false,
  Tabs: [] as string[]
})
const editFormRef = ref()

const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
const userStatus = ref('正常')
const isUserNormal = ref(true)

const products = ref<Product[]>([])
const filteredProducts = ref<Product[]>([])
const pageError = ref('')

const fetchProducts = async () => {
  try {
    const userId = userInfo._id
    const res = await getProductList({ topCate: 1, page: 1, userId })
    if (res.data.code === 200) {
      products.value = res.data.products
      filteredProducts.value = res.data.products
      isUserNormal.value = true
      pageError.value = ''
    } else {
      ElMessage.error('获取商品失败')
    }
  } catch (e: any) {
    if (e.response && e.response.status === 403) {
      isUserNormal.value = false
      pageError.value = e.response.data.message || '当前账号状态异常，无法进行商品管理操作，请联系管理员。'
    } else {
      ElMessage.error('获取商品失败')
    }
  }
}

const fetchCategories = async () => {
  try {
    const res = await request.get('/products/catetopgory')
    if (res.data.code === 200) {
      categories.value = res.data.categories
    }
  } catch (e) {
    console.error('获取分类失败', e)
  }
}

const fetchSubCategories = async (topCategoryId: string) => {
  try {
    const res = await request.get('/products/catesubgory')
    if (res.data.code === 200) {
      // 过滤出属于当前大分类的小分类
      const allSubCategories = res.data.categories
      const filteredSubCategories = allSubCategories.filter((cat: any) => {
        // 确保类型匹配，将ObjectId转换为字符串进行比较
        return cat.parent.toString() === topCategoryId.toString()
      })
      subCategories.value = filteredSubCategories
    }
  } catch (e) {
    console.error('获取小分类失败', e)
  }
}

const openAddDialog = () => {
  addDialogVisible.value = true
  // 重置表单
  addForm.value = {
    name: '',
    description: '',
    price: 0,
    image: '',
    images: [],
    stock: 100,
    topCategory: '',
    subCategory: '',
    isUp: false,
    Tabs: []
  }
}

const handleTopCategoryChange = (value: string) => {
  addForm.value.subCategory = ''
  fetchSubCategories(value)
}

const submitAddForm = async () => {
  try {
    // 从本地存储获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userId = userInfo._id
    
    if (!userId) {
      ElMessage.error('用户信息获取失败，请重新登录')
      return
    }
    
    // 将用户ID添加到表单数据中
    const formData = {
      ...addForm.value,
      userId: userId
    }
    
    const res = await addProduct(formData)
    if (res.data.code === 200) {
      ElMessage.success('添加商品成功')
      addDialogVisible.value = false
      // 重新获取商品列表
      fetchProducts()
    } else {
      ElMessage.error(res.data.message || '添加商品失败')
    }
  } catch (e) {
    ElMessage.error('添加商品失败')
  }
}

const openEditDialog = (row: Product) => {
  editForm.value = {
    _id: row._id,
    name: row.name,
    description: row.description,
    price: row.price,
    image: row.image,
    images: row.images || [],
    stock: row.stock,
    topCategory: row.topCategoryInfo?._id || '', // 修改这里，使用_id而不是name
    subCategory: row.subCategoryInfo?._id || '',
    isUp: row.isUp,
    Tabs: row.Tabs || []
  }
  editDialogVisible.value = true
  
  // 先加载小分类，然后设置选中值
  if (editForm.value.topCategory) {
    fetchSubCategories(editForm.value.topCategory).then(() => {
      // 确保小分类加载完成后再设置选中值
      editForm.value.subCategory = row.subCategoryInfo?._id || ''
    })
  }
}

const handleEditTopCategoryChange = (value: string) => {
  // 清空小分类选择
  editForm.value.subCategory = ''
  // 加载新的小分类列表
  fetchSubCategories(value)
}

const submitEditForm = async () => {
  try {
    // 从本地存储获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userId = userInfo._id
    
    if (!userId) {
      ElMessage.error('用户信息获取失败，请重新登录')
      return
    }
    
    // 将用户ID添加到表单数据中
    const formData = {
      ...editForm.value,
      userId: userId
    }
    
    const res = await updateProduct(editForm.value._id, formData)
    if (res.data.code === 200) {
      ElMessage.success('修改商品成功')
      editDialogVisible.value = false
      // 重新获取商品列表
      fetchProducts()
    } else {
      ElMessage.error(res.data.message || '修改商品失败')
    }
  } catch (e) {
    ElMessage.error('修改商品失败')
  }
}

const handleSearch = () => {
  filteredProducts.value = products.value.filter((item: Product) => {
    const idMatch = !searchForm.value.id || item._id.includes(searchForm.value.id)
    const nameMatch = !searchForm.value.name || item.name.includes(searchForm.value.name)
    const categoryMatch = !searchForm.value.category || item.topCategoryInfo?.name === searchForm.value.category
    const statusMatch = !searchForm.value.status || (searchForm.value.status === '上架' ? item.isUp : !item.isUp)
    return idMatch && nameMatch && categoryMatch && statusMatch
  })
}

const handleReset = () => {
  searchForm.value = { id: '', name: '', category: '', status: '' }
  filteredProducts.value = [...products.value]
}

const handleAdd = () => {
  if (!isUserNormal.value) return
  openAddDialog()
}

const handleEdit = (row: Product) => {
  if (!isUserNormal.value) return
  openEditDialog(row)
}

const handleDelete = async (row: Product) => {
  if (!isUserNormal.value) return
  try {
    // 从本地存储获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userId = userInfo._id
    
    if (!userId) {
      ElMessage.error('用户信息获取失败，请重新登录')
      return
    }
    
    // 检查商品是否在售
    if (row.isUp) {
      await ElMessageBox.confirm(
        `商品「${row.name}」当前为上架状态，删除后商品将无法被用户看到。确定要删除吗？`, 
        '删除确认', 
        {
          type: 'warning',
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true
        }
      )
    } else {
      await ElMessageBox.confirm(
        `确定要删除商品「${row.name}」吗？此操作不可恢复！`, 
        '删除确认', 
        {
          type: 'warning',
          confirmButtonText: '确定删除',
          cancelButtonText: '取消'
        }
      )
    }
    
    // 调用删除API，传递用户ID
    const res = await deleteProduct(row._id, { userId })
    if (res.data.code === 200) {
      ElMessage.success(`删除商品「${row.name}」成功`)
      // 重新获取商品列表
      fetchProducts()
    } else {
      ElMessage.error(res.data.message || '删除商品失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败，请稍后重试')
    }
  }
}

const detailDialogVisible = ref(false)
const detailProduct = ref<Product | null>(null)

const handleViewDetail = (row: Product) => {
  detailProduct.value = row
  detailDialogVisible.value = true
}

onMounted(() => {
  fetchProducts()
  fetchCategories()
  
  // 初始化 Socket.IO 连接并监听状态变更
  if (userInfo._id) {
    initSocket(userInfo._id)
    
    // 监听用户状态变更事件
    onUserStatusChanged((data: any) => {
      if (data.userId === userInfo._id) {
        // 更新本地状态
        if (data.status === '已冻结') {
          isUserNormal.value = false
          pageError.value = data.message
          ElMessage.error(data.message)
        } else if (data.status === '正常') {
          isUserNormal.value = true
          pageError.value = ''
          ElMessage.success(data.message)
          // 重新获取数据
          fetchProducts()
        }
      }
    })
    
    // 监听新公告事件
    onNewAnnouncement((data: any) => {
      ElNotification({
        title: '新公告',
        message: data.message,
        type: 'info',
        duration: 5000
      })
    })
  }
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  offUserStatusChanged()
  offNewAnnouncement()
})
</script>

<template>
  <div>
    <div v-if="!isUserNormal">
      <el-card style="margin: 60px auto; max-width: 480px; text-align: center; color: #e1251b; font-size: 1.2rem;">
        <el-icon style="font-size: 2.5rem; margin-bottom: 12px;"><WarningFilled /></el-icon>
        <div>{{ pageError || '当前账号状态异常，无法进行商品管理操作，请联系管理员。' }}</div>
      </el-card>
    </div>
    <div v-else>
      <!-- 原有商品管理内容 -->
  <el-card>
    <template #header>
      <div class="card-header">
        <span>商品管理</span>
      </div>
    </template>
    <el-form :inline="true" :model="searchForm" class="search-form" size="small">
      <el-form-item label="商品ID">
        <el-input v-model="searchForm.id" placeholder="请输入商品ID" clearable />
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="searchForm.category" placeholder="请选择分类" clearable style="width: 140px;">
              <el-option v-for="cat in categories" :key="cat._id" :label="cat.name" :value="cat.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 140px;">
          <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="danger" plain @click="handleAdd">+ 添加商品</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="filteredProducts" border stripe style="margin-top: 18px;">
      <el-table-column prop="id" label="商品ID" width="100" />
      <el-table-column prop="name" label="商品名称" min-width="200">
        <template #default="scope">
          <span style="color:#e1251b;">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
          <el-table-column label="商品图片" width="120">
            <template #default="scope">
              <el-image 
                :src="scope.row.image" 
                style="width: 50px; height: 50px;"
                fit="cover"
                :preview-src-list="scope.row.images.length > 0 ? scope.row.images : [scope.row.image]"
              />
            </template>
          </el-table-column>
          <el-table-column label="大分类" width="100">
            <template #default="scope">
              <span>{{ scope.row.topCategoryInfo?.name || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="小分类" width="100">
            <template #default="scope">
              <span>{{ scope.row.subCategoryInfo?.name || '-' }}</span>
            </template>
          </el-table-column>
      <el-table-column prop="price" label="价格" width="100">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="80" />
          <el-table-column prop="sales" label="销量" width="80" />
          <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag
                :type="scope.row.isUp ? 'success' : 'danger'"
            disable-transitions
              >{{ scope.row.isUp ? '上架' : '下架' }}</el-tag>
        </template>
      </el-table-column>
          <el-table-column label="操作" width="200">
        <template #default="scope">
              <el-button type="primary" link size="small" @click="handleViewDetail(scope.row)">查看</el-button>
          <el-button type="success" link size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button 
                type="danger" 
                link 
                size="small" 
                @click="handleDelete(scope.row)"
              >
                {{ scope.row.isUp ? '删除(上架中)' : '删除' }}
              </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 18px 0 0 0; text-align: right;">
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="filteredProducts.length"
        :page-size="6"
        :current-page="1"
        style="display:inline-block"
      />
    </div>
  </el-card>

      <!-- 添加商品对话框 -->
      <el-dialog v-model="addDialogVisible" title="添加商品" width="600px">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品描述" prop="description">
            <el-input v-model="addForm.description" type="textarea" :rows="3" placeholder="请输入商品描述" />
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input-number v-model="addForm.price" :min="0" :precision="2" style="width: 100%" />
          </el-form-item>
          <el-form-item label="商品图片" prop="image">
            <el-input v-model="addForm.image" placeholder="请输入商品图片URL" />
          </el-form-item>
          <el-form-item label="库存数量" prop="stock">
            <el-input-number v-model="addForm.stock" :min="0" style="width: 100%" />
          </el-form-item>
          <el-form-item label="大分类" prop="topCategory">
            <el-select v-model="addForm.topCategory" placeholder="请选择大分类" @change="handleTopCategoryChange" style="width: 100%">
              <el-option v-for="cat in categories" :key="cat._id" :label="cat.name" :value="cat._id" />
            </el-select>
          </el-form-item>
          <el-form-item label="小分类" prop="subCategory">
            <el-select v-model="addForm.subCategory" placeholder="请选择小分类" style="width: 100%" :disabled="subCategories.length === 0">
              <el-option v-for="cat in subCategories" :key="cat._id" :label="cat.name" :value="cat._id" />
              <el-option v-if="subCategories.length === 0" disabled label="暂无小分类" value="" />
            </el-select>
            <div v-if="subCategories.length === 0 && addForm.topCategory" style="color: #909399; font-size: 12px; margin-top: 5px;">
              该大分类下暂无小分类，请先添加小分类
            </div>
          </el-form-item>
          <el-form-item label="上架状态">
            <el-switch v-model="addForm.isUp" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddForm">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 编辑商品对话框 -->
      <el-dialog v-model="editDialogVisible" title="编辑商品" width="600px">
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="editForm.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品描述" prop="description">
            <el-input v-model="editForm.description" type="textarea" :rows="3" placeholder="请输入商品描述" />
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input-number v-model="editForm.price" :min="0" :precision="2" style="width: 100%" />
          </el-form-item>
          <el-form-item label="商品图片" prop="image">
            <el-input v-model="editForm.image" placeholder="请输入商品图片URL" />
          </el-form-item>
          <el-form-item label="库存数量" prop="stock">
            <el-input-number v-model="editForm.stock" :min="0" style="width: 100%" />
          </el-form-item>
          <el-form-item label="大分类" prop="topCategory">
            <el-select v-model="editForm.topCategory" placeholder="请选择大分类" @change="handleEditTopCategoryChange" style="width: 100%">
              <el-option v-for="cat in categories" :key="cat._id" :label="cat.name" :value="cat._id" />
            </el-select>
          </el-form-item>
          <el-form-item label="小分类" prop="subCategory">
            <el-select v-model="editForm.subCategory" placeholder="请选择小分类" style="width: 100%" :disabled="subCategories.length === 0">
              <el-option v-for="cat in subCategories" :key="cat._id" :label="cat.name" :value="cat._id" />
              <el-option v-if="subCategories.length === 0" disabled label="暂无小分类" value="" />
            </el-select>
            <div v-if="subCategories.length === 0 && editForm.topCategory" style="color: #909399; font-size: 12px; margin-top: 5px;">
              该大分类下暂无小分类，请先添加小分类
            </div>
          </el-form-item>
          <el-form-item label="上架状态">
            <el-switch v-model="editForm.isUp" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEditForm">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 商品详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="商品详情" width="600px">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品名称">{{ detailProduct?.name }}</el-descriptions-item>
          <el-descriptions-item label="商品描述">{{ detailProduct?.description }}</el-descriptions-item>
          <el-descriptions-item label="商品价格">{{ detailProduct?.price }}</el-descriptions-item>
          <el-descriptions-item label="商品图片">
            <el-image 
              :src="detailProduct?.image" 
              style="width: 100px; height: 100px;"
              fit="cover"
            />
          </el-descriptions-item>
          <el-descriptions-item label="库存数量">{{ detailProduct?.stock }}</el-descriptions-item>
          <el-descriptions-item label="大分类">{{ detailProduct?.topCategoryInfo?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="小分类">{{ detailProduct?.subCategoryInfo?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="上架状态">{{ detailProduct?.isUp ? '上架' : '下架' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailProduct?.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ detailProduct?.updatedAt }}</el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.card-header {
  font-size: 1.2rem;
  font-weight: bold;
}
.search-form {
  margin-bottom: 10px;
}
</style> 